package com.xmb.wechat.view.wechat.chat;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.adapter.ChatMsgAdapter;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.GroupTalkBean;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.bean.WechatMsgBean;
import com.xmb.wechat.bean.WechatMsgBean_;
import com.xmb.wechat.definterface.GroupWhoSendListener;
import com.xmb.wechat.dialog.GroupWhoSendDialog;
import com.xmb.wechat.entity.WechatAppInfoBean;
import com.xmb.wechat.lsn.OnRefreshListener;
import com.xmb.wechat.lsn.SendMsgCenter;
import com.xmb.wechat.util.PicLoadUtils;
import com.xmb.wechat.widget.ChartBar;
import com.xmb.wechat.widget.ChartBarExtend;
import com.xmb.wechat.widget.TitleLayout;

import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * @Author lijiangop
 * @CreateTime 2020/4/14 16:53
 */
public class WechatQunliaoDetailActivity extends BaseActivity implements OnRefreshListener {

    @BindView(R2.id.title_layout)
    TitleLayout    mTitleLayout;
    @BindView(R2.id.iv_chat_bg)
    ImageView      mIvChatBg;
    @BindView(R2.id.msgContent)
    RecyclerView   mRecyclerView;
    @BindView(R2.id.chat_bar)
    ChartBar       mChartBar;
    @BindView(R2.id.layout_add_open)
    ChartBarExtend mChartBarExtend;

    private GroupTalkBean      mGroupTalkBean;
    private ChatMsgAdapter     mAdapter;
    private GroupWhoSendDialog mGroupWhoSendDialog;

    public WechatQunliaoDetailActivity() {
        super(R.layout.activity_wechat_qunliao_detail);
    }

    public static void start(Context context, GroupTalkBean item) {
        Intent intent = new Intent(context, WechatQunliaoDetailActivity.class);
        intent.putExtra("data", item);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        setStatusBarColor(Color.parseColor("#ededed"));
        setNavigationColor(Color.parseColor("#f7f7f7"));

        mChartBar.adjustViewSize();
        mTitleLayout.adjustViewSize();
        //数据
        mGroupTalkBean = (GroupTalkBean) getIntent().getSerializableExtra("data");
        if (mGroupTalkBean == null)
            return;
        mTitleLayout.setTitleLeft(mGroupTalkBean.getGroupName() + "(" + mGroupTalkBean.getGroupMembers() + ")");
        mTitleLayout.setMuteAndStrongRemind(mGroupTalkBean.isNoDisturbing(), false);
        //adapter
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ChatMsgAdapter(this, true, null, mGroupTalkBean, this);
        mRecyclerView.setAdapter(mAdapter);
        //设置聊天背景
        String bg = WechatAppInfoBean.getWechat(this).getChatCommonBG();
        if (TextUtils.isEmpty(mGroupTalkBean.getGroupBg())) {//没有设置个人的背景图
            if (TextUtils.isEmpty(bg)) {
                mAdapter.setIsHasBgPic(false);
                PicLoadUtils.loadChatBg("", mIvChatBg);
            } else {
                PicLoadUtils.loadChatBg(bg, mIvChatBg);
                mAdapter.setIsHasBgPic(true);
            }
        } else {//个人背景不为空
            if (TextUtils.equals(mGroupTalkBean.getGroupBg(), "default")) {
                mAdapter.setIsHasBgPic(false);
                PicLoadUtils.loadChatBg("", mIvChatBg);
            } else {
                PicLoadUtils.loadChatBg(mGroupTalkBean.getGroupBg(), mIvChatBg);
                mAdapter.setIsHasBgPic(true);
            }
        }
        //聊天模块
        mChartBar.init(this, new ChartBar.OnChatBarClickCallBack() {
            @Override
            public void onVoiceClick() {
                mChartBar.hideExpand();
                WechatChatAddVoiceActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean);
            }

            @Override
            public void onAddClick() {
                mChartBar.hideExpand();
                new Handler().postDelayed(() -> mChartBarExtend.setVisibility(View.VISIBLE), 50);
            }

            @Override
            public void onSendClick() {
                KeyboardUtils.hideSoftInput(WechatQunliaoDetailActivity.this);
                if (mGroupWhoSendDialog == null) {
                    mGroupWhoSendDialog = new GroupWhoSendDialog(WechatQunliaoDetailActivity.this,
                            WechatContactBean.instanceNewContactMe(WechatQunliaoDetailActivity.this), mGroupTalkBean, new GroupWhoSendListener() {
                        @Override
                        public void onChoose(WechatContactBean wechatContactBean) {
                            onClickSend(wechatContactBean);
                        }
                    });
                }
                mGroupWhoSendDialog.show();
            }

            @Override
            public void onSendLongClick(String msg) {
                //长按无效
            }
        });
        //聊天模块拓展
        mChartBarExtend.init(new ChartBarExtend.onChatBarExtendClickCallBack() {
            @Override
            public void onVoiceClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddVoiceActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean);
            }

            @Override
            public void onPictureClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddImgActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean);
            }

            @Override
            public void onRedPacketClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddRedpkgActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean);
            }

            @Override
            public void onZhuanZhangClick() {
                //群聊没转账
            }

            @Override
            public void onVideoCallClick() {
                mChartBarExtend.setVisibility(View.GONE);
                new AlertDialog.Builder(WechatQunliaoDetailActivity.this).setItems(new String[]{"视频通话", "语音通话"},
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        WechatChatAddCallActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean, true);
                                        break;
                                    case 1:
                                        WechatChatAddCallActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean, false);
                                        break;
                                }
                            }
                        }).setNegativeButton("取消", null).show();
            }

            @Override
            public void onTimeClick() {
                mChartBarExtend.setVisibility(View.GONE);
                TimePickerView pvTime = new TimePickerBuilder(WechatQunliaoDetailActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        SendMsgCenter.sendTime(new SendMsgCenter.SendMsgListener() {
                            @Override
                            public void onSendSuc() {
                                refresh();
                            }

                            @Override
                            public void onSendError(String errorMsg) {

                            }
                        }, true, mGroupTalkBean.getId(), date);
                    }
                })
                        .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setTitleSize(20)//标题文字大小
                        .setTitleText("时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setSubmitColor(getResources().getColor(R.color.wechat_tab_bg_green))//确定按钮文字颜色
                        .setCancelColor(getResources().getColor(R.color.wechat_tab_bg_green))//取消按钮文字颜色
                        .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                        .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .build();
                pvTime.show();
            }

            @Override
            public void onSystemTipClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddSystipActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean);
            }

            @Override
            public void onBussinessClick() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddBCardsActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean);
            }

            @Override
            public void onRedPacketReceive() {
                mChartBarExtend.setVisibility(View.GONE);
                WechatChatAddRedpkgReceiveActivity.start(WechatQunliaoDetailActivity.this, mGroupTalkBean);
            }
        }, true);
    }

    //刷新数据
    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }

    @Override
    public void refresh() {
        //聊天记录：
        List<WechatMsgBean> msgs = WechatStartApplication.getBoxStore().boxFor(WechatMsgBean.class)
                .query().equal(WechatMsgBean_.talkerID, mGroupTalkBean.getId()).equal(WechatMsgBean_.isRoomChat, true).build().find();
        mAdapter.getData().clear();
        mAdapter.getData().addAll(msgs);
        mAdapter.notifyDataSetChanged();
        mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
    }

    //点击发送按钮
    private void onClickSend(WechatContactBean wechatContactBean) {
        String content = mChartBar.getSendValue();
        if (TextUtils.isEmpty(content))
            return;
        SendMsgCenter.sendString(new SendMsgCenter.SendMsgListener() {
            @Override
            public void onSendSuc() {
                refresh();
                mChartBar.clearInput();
            }

            @Override
            public void onSendError(String errorMsg) {

            }
        }, wechatContactBean.getId(), true, mGroupTalkBean.getId(), content);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mChartBar != null)
            mChartBar.hideExpand();
    }

    @Override
    public void onBackPressed() {
        if (mChartBarExtend.getVisibility() == View.VISIBLE) {
            mChartBarExtend.setVisibility(View.GONE);
        } else if (mChartBar.isEmojiVisible()) {
            mChartBar.hideExpand();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGroupWhoSendDialog != null) {
            mGroupWhoSendDialog.dismiss();
            mGroupWhoSendDialog = null;
        }
    }
}
